var ehconfig = new EHConfig();
var eh = new EH();
var ehutil = new EhUtil();

String.prototype.format = function (param) {
    var reg = /!{([^{}]+)}/gm;
    return this.replace(reg, function (match, name) {
        return param[name];
    });
}

function EhUtil() {

    this.str_format_ellipsis = function (str, length) {
        if (str.length > length)
            return str.substring(0, length) + "......"
        return str;
    }
}

function EHConfig() {


    var datatable_config = {
        "autoWidth": false,
        "ajax": {
            "type": "POST"
        },
        "bFilter": false,//改变每页显示数据数量
        "bLengthChange": false,//搜索条
        "bProcessing": true,
        "oLanguage": {
            "sUrl": "cn.txt"
        }, "fnServerParams": function (aoData) {  //查询条件
            $('textarea.form-filter, select.form-filter, input.form-filter:not([type="radio"],[type="checkbox"])', $("#queryform")).each(function () {
                if ($(this).val() != undefined && $(this).val() != "")
                    aoData[$(this).attr("name")] = $(this).val();
            });
            // $.extend(aoData,$("#queryform").serialize());
        },
        "oLanguage": {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "抱歉， 没有找到",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "没有数据",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            },
            "sZeroRecords": "没有检索到数据",
            "sProcessing": "<img src='/static/img/load.gif' />"
        },
        "pageLength": 20,
        "serverSide": true,
        "createdRow": function ( row, data, index) {  // 创建行回调
            var formats = $(row).find("[format]");
            $.each(formats, function (i, o) {
                var text = $(o).html();
                text = text.format(data);
                $(o).html(text);
            });

            return row;
        }
    };
    this.get_datatable_config = function (setting) {
        $.extend(datatable_config, setting);
        return datatable_config;
    }
    
    this.dtconfig = function (dtid) {
        var columns = [];
        var columnDefs = [];
        var dtObj =  $("#" + dtid);
        var dataUrl = dtObj.attr("data-url");
        // 读取列配置
        $.each(dtObj.find("tr").eq(0).find("td"),function(i,obj){
            var valObj = $(obj).parent("tr").next().find("td").eq(i); // 用于显示的对象
            var title = $(obj).html();
            var data = $(obj).attr("data") == undefined ? null : $(obj).attr("data") ;
            var width = $(obj).attr("width");
            var orderable = $(obj).attr("orderable") == undefined ? false : $(obj).attr("orderable") ;
            var visible = $(obj).attr("visible")  == undefined ? true : $(obj).attr("visible") ;
            var format  = $(valObj).attr("data-dt-format")  == undefined ? null :  $(valObj).attr("data-dt-format");
            columns[i] =  {"title": title, "data": data , "width": width, "orderable": orderable, "visible" : visible};

            // 判断列是否需要渲染
            if (format != null) {
                var tdObj = $(obj).parent("tr").next().find("td").eq(i);
                columnDefs[columnDefs.length] = {
                    "targets": i,
                    "render": function (data, type, row, meta) {
                        var text = $(valObj).html().format(row);
                        if (format == "js" && text!='' ) {
                            text = eval( text );
                        } else if (format == "dict") {
                            var dicts = $(valObj).attr("data-dict");
                            dict = eval("(" + dicts + ")");
                            text = dict[data];
                        }
                        return text;
                    }
                }
            }
        });
        
        var setting = {
            "ajax": {
                "url": dataUrl,
                "type": "POST"
            },
            "columns": columns,
            "columnDefs" : columnDefs,
            "order": [
                [1, "desc"]
            ]
        };
        
        $.extend(datatable_config, setting);
        return datatable_config;
    }
    
}


function EH() {
    var _dtid = "data-table";                // datatables控件默认ID
    var _attr_dt_clear = "data-dt-clear";    // datatables控件 搜索表单 重置扩展自定义属性
    var _attr_dt_query = "data-dt-query";    // datatables控件 搜索扩展自定义属性  
    var _attr_dt_oper = "data-dt-oper";      // datatables控件 表单操作 vakues: refresh 
    var _self = this;
    
    this.init = function () {
        _self.initRadio();
        _self.bindForm();
        _self.bindDatapicker();
        _self.bindDataOpt();
        _self.layerClose();
        _self.initChecks();
        _self.datatableTools();
        _self.layerImg();
    };

    /**
     * 刷新表格
     * @param dtId 表格ID
     */
    this.datatableRefresh = function (dtId) {
        $('#' + dtId).DataTable().draw();
    };

    this.datatableTools = function () {
        $("button[datatable-clear]").click(function () {
            var datatable = $(this).attr(_attr_dt_clear);
            $(this).parent("form")[0].reset();
            _self.datatableRefresh(datatable ? datatable : _dtid);
        });

        $("button[" + _attr_dt_clear + "]").click(function () {
            var datatable = $(this).attr(_attr_dt_clear);
            $(this).parent("form")[0].reset();
            _self.datatableRefresh(datatable ? datatable : _dtid);
        });

        $("button[" + _attr_dt_query + "]").click(function () {
            var datatable = $(this).attr(_attr_dt_query);
            _self.datatableRefresh(datatable ? datatable : _dtid);
        })
    };

    this.initChecks = function () {
        $('.i-checks').iCheck({
            checkboxClass: 'icheckbox_square-green',
            radioClass: 'iradio_square-green',
        });
    };
    this.initSelect = function () {
        $.each($("select[data-sel]"), function (i, o) {
            var val = $(o).attr("data-sel");
            $(o).val(val);
        });
    };


    this.bindDataOpt = function () {
        $(document).on('click', "a[data-opt]", function () {
            var url = $(this).attr("data-opt-url");
            var fun = $(this).attr("data-opt-fun");
            var pams = $(this).attr("data-opt-pams");
            var refreshTableId = $(this).attr("data-refresh-dt");

            parent.layer.confirm('确定操作？', function (result) {
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: url,
                    dataType: "json",
                    data: eval('(' + pams + ')'),// 你的formid
                    async: false,
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        toastr.error("操作失败,错误代码[" + XMLHttpRequest.status + "]");
                    },
                    success: function (data) {
                        layClose()
                        if (data.success) {
                            toastr.success("操作成功", '成功');
                            eval(fun);
                            $("#" + refreshTableId).DataTable().draw();
                        } else {
                            toastr.error(data.msg || "失败");
                        }
                    }
                });

            })

        });

        $(document).on('click', "a[" + _attr_dt_oper + "]", function () {
            
            var tabObjId = $(this).parentsUntil(".table").last().parent().attr("id");
            
            var oper = $(this).attr(_attr_dt_oper);
            var confirm = $(this).attr("data-confirm");
            var url = $(this).attr("href");
            if (url.indexOf("?") != -1) {
                url = url + "&ajax=true";
            } else {
                url = url + "?ajax=true";
            }

            if (confirm != null) {
                parent.layer.confirm('确定操作？', function (result) {
                    _self.doAjax(url, oper, tabObjId);
                    layClose();
                });
            } else {
                _self.doAjax(url, oper, tabObjId);
            }
            return false;// 屏蔽href的超链接
        });
    };

    this.bindDatapicker = function () {
        if ($("div[datepicker]").length == 0) {
            return;
        }
        $("div[datepicker]").datepicker({
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: false,
            autoclose: true,
            format: 'yyyy-mm-dd',
            language: 'cn'
        });
    };

    this.layerClose = function () {
        if ($("a[layer-close]").length == 0) {
            return;
        }
        $("a[layer-close]").click(function () {
            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            parent.layer.close(index); //再执行关闭
        })

    }
    this.bindForm = function () {

        if ($("form[data-ajax]").length == 0) {
            return;
        }
        for (var i = 0; i < $("form[data-ajax]").length; i++) {
            var ext = _self.initExtValidate($($("form[data-ajax]")[i]));
            $($("form[data-ajax]")[i]).validate({
                submitHandler: function (form) {
                    var data = $(form).serialize();
                    var action = $(form).attr("action");
                    var oper = $(form).attr("data-ajax");
                    var _fun = $(form).attr("data-function");
                    var _form_before = $(form).attr("form-before");

                    if (_form_before) {
                        if (!eval(_form_before))return;
                    }

                    $.ajax({
                        cache: false,
                        type: "POST",
                        url: action,
                        dataType: "json",
                        data: data,// 你的formid
                        async: false,
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            toastr.error("操作失败,错误代码[" + XMLHttpRequest.status + "]");
                        },
                        success: function (data) {
                            if (data.success) {
                                if (oper) {
                                    toastr.info(data.msg || "成功", '提醒', {
                                        call: function () {
                                            location.href = oper;
                                        }
                                    });
                                }
                                if (_fun) {
                                    eval(_fun + "(" + JSON.stringify(data.data) + ")");
                                }


                            } else {
                                toastr.error(data.msg || "失败");
                            }
                        }
                    });
                },
                rules: ext,
                errorPlacement: function(error, element) {
                    element.parent().append(error);
                    if(element.hasClass("i-checks")){
                        element.parents(".form-group").find("div").first().append(error);
                    }else{
                        element.parent().append(error);
                    }
                }

            });

        }

    };
    this.initExtValidate = function (form) {
        var retObj = {};
        if (form.find("input[isMobile]").attr("name")) {  //额外增加手机验证功能
            retObj[form.find("input[isMobile]").attr("name")] = "isMobile";
        }
        if (form.find("input[isIdCardNo]").attr("name")) {  //额外增加身份证验证
            retObj[form.find("input[isIdCardNo]").attr("name")] = "isIdCardNo";
        }
        if(form.find("input[stringCheck]").attr("name")){  //额外增加身份证验证
            retObj[form.find("input[stringCheck]").attr("name")] = "stringCheck";
        }
        if(form.find("input[isChina]").attr("name")){  //不能包含中文
            retObj[form.find("input[isChina]").attr("name")] = "isChina";
        }
        if(form.find("input[isTel]").attr("name")){  //不能包含中文
            retObj[form.find("input[isTel]").attr("name")] = "isTel";
        }
        return retObj;
    },
        this.initRadio = function () {
            $.each($(":radio[data-checked]"), function (i, o) {
                var eleName = $(o).attr("name");

                var val = $(o).attr("data-checked");
                $(":radio[name='" + eleName + "'][value='" + val + "']").attr("checked", true);
            });
        };

    this.layerImg = function () {
        $("body").delegate("img[data-img]", "click", function () {
            var self=$(this);
            var image = new Image()
            image.src = self.attr("src");
            var halfwindowWidth=$(window).width()/2;
            var naturalWidth = image.width>halfwindowWidth?halfwindowWidth:image.width;
            var src = $(this).attr("src") || "/static/img/default_pic_no.jpg";
            parent.layer.open({
                type: 1,
                title: false,
                closeBtn: 1,
                area: naturalWidth+'px',
                skin: 'layui-layer-nobg', //没有背景色
                shadeClose: true,
                content: "<img width='100%' src='" + src + "'>",
            })
        })

    }

    this.doAjax = function (url, oper, dtid) {
        $.ajax({
            cache: false,
            type: "POST",
            url: url,
            dataType: "json",
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                toastr.error("操作失败,错误代码[" + XMLHttpRequest.status + "]");
            },
            success: function (data) {
                if (data.success) {
                    toastr.info(data.msg || "成功", '提醒', {
                        call: function () {
                            if (oper == "refresh") {
                                _self.datatableRefresh(dtid);
                            }
                        }
                    });
                } else {
                    toastr.error(data.msg || "失败");
                }
            }
        });
    };


}

$(document).ready(function () {
    eh.init();

});

function getRightFrame() {
    return top.window.frames[0];
}

function layClose() {
    parent.layer.closeAll();
}

jQuery.fn.extend({
    ehdatatable: function() {
        var id = $(this).attr("id");
        return $(this).DataTable(ehconfig.dtconfig(id));
    }
});